﻿using Microsoft.Extensions.Caching.Distributed;
using System.Text.Json;

namespace PetAdoptApi.Extensions;

public static class DistributedCacheExt
{
    public static async Task<T?> GetValueAsync<T>(this IDistributedCache cache , string cacheKey) where T : class
    {
        var value =await cache.GetStringAsync(cacheKey);
        if (value is null) return null;
        return JsonSerializer.Deserialize<T>(value);
    }

    public static async Task SetValueAsync(this IDistributedCache cache,string cacheKey,object? cacheValue) => await SetValueAsync(cache,cacheKey, cacheValue, null);

    public static async Task SetValueAsync(this IDistributedCache cache, string cacheKey, object? cacheValue, TimeSpan? expireTime)
    {
        var cacheOption = new DistributedCacheEntryOptions();
        if(expireTime is not null) cacheOption.AbsoluteExpirationRelativeToNow = expireTime;
        string value = cacheValue is null ? "" : JsonSerializer.Serialize(cacheValue);
        await cache.SetStringAsync(cacheKey, value);
    }
}

